package com.itheima.bos.web.action.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.UserService;
import com.itheima.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User> {

	@Autowired
	private UserService userService;

	/*
	 * 用户登录的方法,基于shiro登录
	 */
	@Action(value = "user_login", results = { @Result(name = "success", type = "json") })
	public String login() {

		Map<String, Integer> result = new HashMap<>();

		Subject subject = SecurityUtils.getSubject();

		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());

		try {
			subject.login(token);
			// 登录成功
			result.put("status", 1);
		} catch (UnknownAccountException e) {
			// 用户名错误
			result.put("status", 2);
		} catch (IncorrectCredentialsException e) {
			// 密码错误
			result.put("status", 3);
		}

		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}

	/*
	 * 用户注销的方法.基于Subject注销
	 */
	@Action(value = "user_logout", results = {
			@Result(name = "success", type = "redirect", location = "./login.html") })
	public String logout() {

		Subject subject = SecurityUtils.getSubject();

		subject.logout();

		return SUCCESS;
	}

	/*
	 * 查询所有的用户
	 */
	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String list() {

		List<User> usrs = userService.findAll();

		ActionContext.getContext().getValueStack().push(usrs);

		return SUCCESS;
	}

	/*
	 * 保存用户
	 */
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value = "user_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/system/userlist.html") })
	public String save() {

		userService.save(model,roleIds);
		
		return SUCCESS;
	}
}
